package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Circuit;
import softswitch.model.Restriction;


@Stateless
public class RestrictionDAO {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Restriction getById(Integer id){	
		return em.find(Restriction.class, id);
	}
	    
    public Restriction save(Restriction restriction) {
    	em.persist(restriction); 
    	return restriction;
    }
    
    public Restriction update(Restriction restriction) {
    	return em.merge(restriction);
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Restriction.class, id));	
    }
    
	@SuppressWarnings("unchecked")
    public List<Restriction> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM Restriction e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
    	if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
    //---------------------------------------------------------------------------------
    
    @SuppressWarnings("unchecked")
    public List<Restriction> listByCircuit(Circuit circuit) {    	
    	List<Restriction> results = null;
    	Query query = em.createQuery("SELECT e FROM Restriction e WHERE e.circuit=:circuit");
		query.setParameter("circuit", circuit);
		try {
			results = query.getResultList(); 
        }
    	catch (Exception e) {
			e.printStackTrace();
		}
        return results;
    }
	
}

